package com.ec50n9.server.controllerAdvice

import com.ec50n9.server.common.ApiException
import com.ec50n9.server.module.common.AjaxResult
import com.ec50n9.server.module.common.AppCode
import com.ec50n9.server.module.common.BaseCode
import org.springframework.beans.factory.annotation.Value
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.multipart.MaxUploadSizeExceededException

/**
 * 全局错误处理
 */
@RestControllerAdvice
class ExceptionAdvice {

    @Value("\${spring.servlet.multipart.max-file-size}")
    var maxFileSize: String = ""

    @ExceptionHandler
    fun apiHandler(exception: ApiException): AjaxResult<Nothing> {
        exception.printStackTrace()
        return AjaxResult.fail(exception.statusCode, exception.message)
    }

    @ExceptionHandler
    fun validHandler(exception: MethodArgumentNotValidException): AjaxResult<Nothing> {
        val msg = exception.bindingResult.allErrors[0].defaultMessage
        println(msg)
        return AjaxResult.fail(BaseCode.VALIDATE_ERROR, msg)
    }

    @ExceptionHandler
    fun dataIntegrityViolationHandler(exception: DataIntegrityViolationException): AjaxResult<Nothing> {
        println(exception.message)
        return AjaxResult.fail(AppCode.DATA_INTEGRITY_VIOLATION)
    }

    @ExceptionHandler
    fun maxUploadSize(exception: MaxUploadSizeExceededException): AjaxResult<Nothing> {
        return AjaxResult.fail(AppCode.OBJECT_NOT_SUPPORTED, "单个文件大小不可超过$maxFileSize")
    }

    @ExceptionHandler
    fun baseHandler(exception: Exception): AjaxResult<Nothing> {
        exception.printStackTrace()
        return AjaxResult.fail(BaseCode.FAILED)
    }
}